using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Expressions;
using Rotempco.Core.ORM.Objects;
using Rotempco.Core.Web.CRUD.Objects.Enums;

namespace Rotempco.Core.Web.CRUD.Logic
{
    public class PagingContainerHelper<T>
    {
        public static PagingContainer GetPagingContainer<TReturn>(Expression<Func<T, TReturn>> defaultSortParameter, bool decending = false)
        {
            HttpRequest request = HttpContext.Current.Request;
            PagingContainer pagingContainer = new PagingContainer();

            int pageNumber;
            if (request == null || string.IsNullOrWhiteSpace(request["PageNumber"]) || !int.TryParse(request["PageNumber"], out pageNumber))
                pagingContainer.PageNumber = 1;
            else
                pagingContainer.PageNumber = pageNumber;

            int pageSize;
            if (request == null || string.IsNullOrWhiteSpace(request["PageSize"]) || !int.TryParse(request["PageSize"], out pageSize))
                pagingContainer.PageSize = (int)PagingPageSizeEnum._2;
            else
                pagingContainer.PageSize = pageSize;


            if (request == null || string.IsNullOrWhiteSpace(request["TableName"]))
                pagingContainer.TableName = ((MemberExpression)defaultSortParameter.Body).Expression.Type.Name;
            else
                pagingContainer.TableName = request["TableName"];

            if (request == null || string.IsNullOrWhiteSpace(request["ColumnName"]))
                pagingContainer.ColumnName = ((MemberExpression)defaultSortParameter.Body).Member.Name;
            else
                pagingContainer.ColumnName = request["ColumnName"];

            if (request != null && !string.IsNullOrWhiteSpace(request["Descending"]))
            {
                if (request["Descending"] == "True")
                    pagingContainer.Descending = true;
                else
                    pagingContainer.Descending = false;
            }
            else
            {
                pagingContainer.Descending = decending;
                pagingContainer.DefaultSortOrderDecending = decending;
            }
            //if (request == null || request["Descending"] != "True")
            //    pagingContainer.Descending = false;
            //else 
            //    pagingContainer.Descending = true;

            return pagingContainer;
        }

    }
}